package com.gzc.just.play.last.war.common.handler;

import com.gzc.just.play.last.war.common.serializer.MessageSerializer;
import com.gzc.just.play.last.war.common.serializer.MessageDeserializerFactory;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 简化的消息路由器
 * 使用非泛型接口和枚举反序列化器，提高性能和可维护性
 */
public class SimpleMessageRouter {
    private static final Logger logger = LoggerFactory.getLogger(SimpleMessageRouter.class);
    
    // 消息ID到处理器的映射
    private final Map<Integer, SimpleMessageHandler> handlers = new ConcurrentHashMap<>();
    
    // 消息序列化器
    private final MessageSerializer messageSerializer;
    
    // 消息反序列化器工厂
    private final MessageDeserializerFactory deserializerFactory;
    
    public SimpleMessageRouter(MessageSerializer messageSerializer, MessageDeserializerFactory deserializerFactory) {
        this.messageSerializer = messageSerializer;
        this.deserializerFactory = deserializerFactory;
        logger.info("Created SimpleMessageRouter with message serializer and deserializer factory");
    }
    
    /**
     * 注册消息处理器
     * @param handler 消息处理器
     */
    public void registerHandler(SimpleMessageHandler handler) {
        handlers.put(handler.getMessageId(), handler);
        logger.info("Registered message handler: {} for message ID: {}", 
                   handler.getName(), handler.getMessageId());
    }
    
    /**
     * 处理接收到的消息
     * @param ctx Netty通道上下文
     * @param messageId 消息ID
     * @param bytes 消息字节数据
     */
    public void handleMessage(ChannelHandlerContext ctx, int messageId, byte[] bytes) {
        try {
            // 首先检查是否有反序列化器支持此消息
            if (deserializerFactory == null || !deserializerFactory.supportsMessage(messageId)) {
                logger.warn("No deserializer found for message ID: {}", messageId);
                return;
            }
            
            // 查找对应的处理器
            SimpleMessageHandler handler = handlers.get(messageId);
            if (handler == null) {
                logger.warn("No handler found for message ID: {}", messageId);
                return;
            }
            
            // 使用工厂创建反序列化器并反序列化消息
            Object message = deserializerFactory.createDeserializer(messageId).deserialize(bytes);
            if (message == null) {
                logger.error("Failed to deserialize message with ID: {}", messageId);
                return;
            }
            
            // 处理消息
            handler.handle(message, ctx);
            
        } catch (Exception e) {
            logger.error("Error handling message with ID: {}", messageId, e);
        }
    }
    
    /**
     * 获取已注册的处理器数量
     */
    public int getHandlerCount() {
        return handlers.size();
    }
    
    /**
     * 检查是否有指定ID的处理器
     */
    public boolean hasHandler(int messageId) {
        return handlers.containsKey(messageId);
    }
    
    
}